/*
 *    Copyright(c)2023-2024
 *    项目名称:hello-world
 *    文件名称:SysRoleMenuServiceImpl.java
 *    Date:2023/11/27 下午9:06
 *    Author:赵士杰
 */

package com.hw.system.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hw.system.admin.mapper.SysRoleMenuMapper;
import com.hw.system.admin.pojo.SysRoleMenu;
import com.hw.system.admin.service.ISysRoleMenuService;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 角色和菜单关联表 服务实现类
 * </p>
 *
 * @author 赵士杰
 * @since 2023-11-27 08:12:41
 */
@Service
public class SysRoleMenuServiceImpl extends ServiceImpl<SysRoleMenuMapper, SysRoleMenu> implements ISysRoleMenuService {

    @Override
    public boolean addRoleMenu(Long roleId, List<Long> menuIds) {
        deleteByRoleId(roleId);

        //一对多，roleId对应每个menuId，批量插入数据库
        List<SysRoleMenu> roleMenuList = menuIds.parallelStream()
                .map(r -> new SysRoleMenu(roleId, r))
                .collect(Collectors.toList());

        return saveOrUpdateBatch(roleMenuList);
    }

    /**
     * 根据角色ID删除角色菜单关联记录
     *
     * @param roleId 角色ID
     * @return 删除结果，true表示删除成功，false表示删除失败
     */
    private boolean deleteByRoleId(Long roleId) {
        LambdaQueryWrapper<SysRoleMenu> deleteWrapper = new LambdaQueryWrapper<>();
        deleteWrapper.eq(SysRoleMenu::getRoleId, roleId);
        return remove(deleteWrapper);
    }

}
